package com.vivachek.protocol.process

import com.vivachek.protocol.END
import com.vivachek.protocol.START
import com.vivachek.protocol.exception.CRCException
import com.vivachek.protocol.exception.NotSupportProtocolException
import com.vivachek.protocol.utils.CRC16


/**
 * @Author: YCB
 * @Time: 2022/9/26 18:46
 * @Email: congbin.yuan@vivachek.com
 * @Description: 校验CRC
 *
 */
internal class VerifyCRCProcess : AbsProcess() {

    override fun convert(data: List<Int>,origin:List<Int>) {
        if (data.size < 6) {
            throw CRCException(data)
        }
        if (data.first() == START && data.last()== END) {
            val calc = data.subList(1,data.size-5)
            val originCrc = data.subList(data.size-5,data.size-1).toIntArray()
            val s = CRC16.calcCrc16(calc.toMutableList().map { it.toByte() }.toByteArray())
            val calcCRC = String.format("%04X", s).map { it.toString().toInt(16) }
            if (!originCrc.contentEquals(swap(calcCRC))){
                throw CRCException(data)
            }
            try {
                next?.convert(calc,data)
            }catch (e: NotSupportProtocolException){
                e.printStackTrace()
                throw NotSupportProtocolException("${e.message?:""}:$data")
            }
            return
        }
        throw RuntimeException("数据不完整:$data")
    }
    private fun swap(crc:List<Int>):IntArray{
        if (crc.size==4) {
            return intArrayOf(crc[2],crc[3],crc[0],crc[1])
        }
        return crc.toIntArray()
    }
}